package com.jm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jm.annotation.SystemLog;
import com.jm.constants.SystemConstants;
import com.jm.domain.ResponseResult;
import com.jm.domain.entity.Comment;
import com.jm.domain.entity.Role;
import com.jm.domain.entity.User;
import com.jm.domain.entity.UserRole;
import com.jm.domain.vo.PageVo;
import com.jm.domain.vo.UserInfo;
import com.jm.domain.vo.UserOneVo;
import com.jm.domain.vo.UserVo;
import com.jm.enums.AppHttpCodeEnum;
import com.jm.exception.SystemException;
import com.jm.mapper.UserMapper;
import com.jm.service.CommentService;
import com.jm.service.RoleService;
import com.jm.service.UserRoleService;
import com.jm.service.UserService;
import com.jm.utils.BeanCopyUtils;
import com.jm.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResponseResult getUserInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据id，查询用户信息
        User user = getById(userId);
        //封装vo
        UserInfo userInfo = BeanCopyUtils.copyBean(user, UserInfo.class);
        return ResponseResult.okResult(userInfo);
    }

    @Override
    @SystemLog(businessName = "更新用户信息")
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult register(User user) {
        //信息校验
        //1数据非空校验
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        //2数据存在校验
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if(emailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //密码加密处理
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        //用户信息存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult listUser(Integer pageNum, Integer pageSize, String userName, String phonenumber, String status) {
        //查询条件
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(userName!=null&&userName!="",User::getUserName,userName);
        queryWrapper.eq(phonenumber!=null&&phonenumber!="",User::getPhonenumber,phonenumber);
        queryWrapper.eq(status!=null&&status!="",User::getStatus,status);
        //分页查询
        Page<User> page=new Page<>(pageNum,pageSize);
        page(page, queryWrapper);
        //封装vo
        List<UserVo> userVos = BeanCopyUtils.copyBeanList(page.getRecords(), UserVo.class);
        return ResponseResult.okResult(new PageVo(userVos,page.getTotal()));
    }

    @Autowired
    private UserRoleService userRoleService;

    @Override
    @Transactional
    public ResponseResult saveUser(User user) {
        //保存用户信息，到user表
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
        //获取roleIds，添加用户角色关系表
        List<UserRole> userRoleList = user.getRoleIds().stream()
                .map(roleId -> new UserRole(user.getId(), Long.valueOf(roleId)))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoleList);
        return ResponseResult.okResult();
    }

    @Autowired
    private CommentService commentService;
    @Override
    @Transactional
    public ResponseResult deleteUser(Long id) {
        //从用户角色关系表，删除相关数据
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        userRoleService.remove(queryWrapper);
        //从user表，删除用户信息
        removeById(id);
        //移除删除用户的评论，并删除回复该用户的评论(移除删除评论下的子评论)
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper=new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getCreateBy,id).or().eq(Comment::getToCommentUserId,id);
        commentService.remove(commentLambdaQueryWrapper);
        return ResponseResult.okResult();
    }

    @Autowired
    private RoleService roleService;

    @Override
    @Transactional
    public ResponseResult getUserById(Long id) {
        //roleIds：用户所关联的角色id列表 List<String>
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoleList = userRoleService.list(queryWrapper);
        List<String> roleIds = userRoleList.stream()
                .map(userRole -> userRole.getRoleId().toString())
                .collect(Collectors.toList());
        //roles：所有角色的列表 List<Role>
        LambdaQueryWrapper<Role> roleQueryWrapper=new LambdaQueryWrapper<>();
        roleQueryWrapper.eq(Role::getStatus, SystemConstants.STATUS_NORMAL);
        List<Role> roles = roleService.list(roleQueryWrapper);
        //user：用户信息 UserOneVo
        User user = getBaseMapper().selectById(id);
        UserOneVo userOneVo = BeanCopyUtils.copyBean(user, UserOneVo.class);
        Map<String,Object> map=new HashMap<>();
        map.put("roleIds",roleIds);
        map.put("roles",roles);
        map.put("user",userOneVo);

        return ResponseResult.okResult(map);
    }

    @Override
    @Transactional
    public ResponseResult updateUser(User user) {
        //保存用户到user表
        updateById(user);
        //删除用户角色表的相应关系
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(queryWrapper);
        //添加新的用户角色关系
        List<UserRole> userRoleList = user.getRoleIds().stream()
                .map(roleId -> new UserRole(user.getId(), Long.valueOf(roleId)))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoleList);
        return ResponseResult.okResult();
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        int count = count(queryWrapper);
        return count>0;
    }
    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName,nickName);
        int count = count(queryWrapper);
        return count>0;
    }
    private boolean emailExist(String email) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,email);
        int count = count(queryWrapper);
        return count>0;
    }
}
